package com.hula.onion.book.server.spider.platforms.jrjc;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;

/**
 * Created by work on 2018/3/4.
 */
@Component
public class JinRiJieCaiSpiderHelper {
    private static final Logger logger = LoggerFactory.getLogger(JinRiJieCaiSpiderHelper.class);

    public Map<String, Object> installRequestParams(LoginForm loginForm) {
        Map<String, Object> params = new JSONObject();
        params.put("phoneNumber", loginForm.getUserName().trim());
        params.put("password", loginForm.getPassword().trim());
        return params;
    }

    /**
     * 解析账户余额
     *
     * @param html
     * @return
     */
    public CommonResponse parseAccountBalance(String html) {
        if (StringUtils.isEmpty(html)) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
        try {
            Document document = Jsoup.parse(html);
            Element el = document.select("#userTotalAmount").first();
            String amount = el.text();
            Element jcbEl = document.selectFirst("table.jcb-profit-table");
            Elements jcbEls = jcbEl.getAllElements();
            String yesterdayIntrest = jcbEls.get(5).text();
            String jcbTotalIntrest = jcbEls.get(8).text();
            AccountInfo accountInfo = new AccountInfo();
            accountInfo.setAmount(new BigDecimal(amount));
            accountInfo.setTotalIntrest(new BigDecimal(jcbTotalIntrest));
            accountInfo.setYesterdayIntrest(new BigDecimal(yesterdayIntrest));
            return new CommonResponse(accountInfo);
        } catch (Exception e) {
            logger.error("[JinRiJieCaiSpiderHelper] parseAccountBalance fail!", e);
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
    }
}
